package com.example.screenrecorder;

import android.app.Service;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureRequest;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.util.Size;
import android.view.Surface;
import android.view.WindowManager;
import android.widget.FrameLayout;

import androidx.core.content.ContextCompat;

import java.util.Arrays;
import java.util.List;

public class CameraOverlay extends Service {
    
    private WindowManager windowManager;
    private CameraPreviewView cameraView;
    private CameraDevice cameraDevice;
    private CameraCaptureSession captureSession;
    private HandlerThread backgroundThread;
    private Handler backgroundHandler;
    private boolean isVisible = false;
    
    private String frontCameraId;
    private String backCameraId;
    private boolean useFrontCamera = true;
    private boolean useBackCamera = false;
    private int overlayPositionX = 50; // 百分比
    private int overlayPositionY = 50;
    private int overlaySize = 30; // 百分比
    private boolean beautyFilterEnabled = false;
    
    @Override
    public void onCreate() {
        super.onCreate();
        windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        startBackgroundThread();
        initializeCameraIds();
    }
    
    @Override
    public int onStartCommand(android.content.Intent intent, int flags, int startId) {
        if (intent != null) {
            String action = intent.getAction();
            if ("show_camera".equals(action)) {
                boolean front = intent.getBooleanExtra("use_front_camera", true);
                boolean back = intent.getBooleanExtra("use_back_camera", false);
                showCameraOverlay(front, back);
            } else if ("hide_camera".equals(action)) {
                hideCameraOverlay();
            } else if ("switch_camera".equals(action)) {
                switchCamera();
            } else if ("update_position".equals(action)) {
                int x = intent.getIntExtra("position_x", 50);
                int y = intent.getIntExtra("position_y", 50);
                int size = intent.getIntExtra("size", 30);
                updateOverlayPosition(x, y, size);
            }
        }
        return START_STICKY;
    }
    
    private void initializeCameraIds() {
        CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
            for (String cameraId : cameraManager.getCameraIdList()) {
                CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
                Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
                if (facing != null) {
                    if (facing == CameraCharacteristics.LENS_FACING_FRONT) {
                        frontCameraId = cameraId;
                    } else if (facing == CameraCharacteristics.LENS_FACING_BACK) {
                        backCameraId = cameraId;
                    }
                }
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    
    private void showCameraOverlay(boolean front, boolean back) {
        if (isVisible) return;
        
        useFrontCamera = front;
        useBackCamera = back;
        
        cameraView = new CameraPreviewView(this);
        
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O ?
                        WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY :
                        WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                        WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
                PixelFormat.TRANSLUCENT
        );
        
        // 设置位置和大小
        updateOverlayLayout(params);
        
        windowManager.addView(cameraView, params);
        isVisible = true;
        
        // 打开摄像头
        openCamera();
    }
    
    private void hideCameraOverlay() {
        if (!isVisible || cameraView == null) return;
        
        closeCamera();
        windowManager.removeView(cameraView);
        cameraView = null;
        isVisible = false;
    }
    
    private void switchCamera() {
        if (!isVisible) return;
        
        closeCamera();
        useFrontCamera = !useFrontCamera;
        openCamera();
    }
    
    private void updateOverlayPosition(int x, int y, int size) {
        overlayPositionX = x;
        overlayPositionY = y;
        overlaySize = size;
        
        if (isVisible && cameraView != null) {
            WindowManager.LayoutParams params = (WindowManager.LayoutParams) cameraView.getLayoutParams();
            updateOverlayLayout(params);
            windowManager.updateViewLayout(cameraView, params);
        }
    }
    
    private void updateOverlayLayout(WindowManager.LayoutParams params) {
        // 获取屏幕尺寸
        android.graphics.Point size = new android.graphics.Point();
        windowManager.getDefaultDisplay().getSize(size);
        
        // 计算实际位置和大小
        int overlayWidth = (int) (size.x * overlaySize / 100.0);
        int overlayHeight = (int) (overlayWidth * 0.75); // 4:3 比例
        
        params.width = overlayWidth;
        params.height = overlayHeight;
        params.x = (int) (size.x * overlayPositionX / 100.0) - overlayWidth / 2;
        params.y = (int) (size.y * overlayPositionY / 100.0) - overlayHeight / 2;
    }
    
    private void openCamera() {
        CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        String cameraId = useFrontCamera ? frontCameraId : backCameraId;
        
        if (cameraId == null) return;
        
        // 检查摄像头权限
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) 
                != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                cameraManager.openCamera(cameraId, new CameraDevice.StateCallback() {
                    @Override
                    public void onOpened(CameraDevice camera) {
                        cameraDevice = camera;
                        createCameraPreviewSession();
                    }
                    
                    @Override
                    public void onDisconnected(CameraDevice camera) {
                        camera.close();
                        cameraDevice = null;
                    }
                    
                    @Override
                    public void onError(CameraDevice camera, int error) {
                        camera.close();
                        cameraDevice = null;
                    }
                }, backgroundHandler);
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    
    private void closeCamera() {
        if (captureSession != null) {
            captureSession.close();
            captureSession = null;
        }
        if (cameraDevice != null) {
            cameraDevice.close();
            cameraDevice = null;
        }
    }
    
    private void createCameraPreviewSession() {
        if (cameraDevice == null || cameraView == null) return;
        
        try {
            Surface previewSurface = cameraView.getSurface();
            if (previewSurface == null) return;
            
            CaptureRequest.Builder builder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            builder.addTarget(previewSurface);
            
            // 设置4K录制（如果支持）
            if (useBackCamera) {
                builder.set(CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE, 
                           CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE_ON);
            }
            
            cameraDevice.createCaptureSession(Arrays.asList(previewSurface),
                    new CameraCaptureSession.StateCallback() {
                        @Override
                        public void onConfigured(CameraCaptureSession session) {
                            captureSession = session;
                            try {
                                CaptureRequest request = builder.build();
                                captureSession.setRepeatingRequest(request, null, backgroundHandler);
                            } catch (CameraAccessException e) {
                                e.printStackTrace();
                            }
                        }
                        
                        @Override
                        public void onConfigureFailed(CameraCaptureSession session) {
                            // 配置失败
                        }
                    }, backgroundHandler);
                    
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    
    private void startBackgroundThread() {
        backgroundThread = new HandlerThread("CameraBackground");
        backgroundThread.start();
        backgroundHandler = new Handler(backgroundThread.getLooper());
    }
    
    private void stopBackgroundThread() {
        if (backgroundThread != null) {
            backgroundThread.quitSafely();
            try {
                backgroundThread.join();
                backgroundThread = null;
                backgroundHandler = null;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        hideCameraOverlay();
        stopBackgroundThread();
    }
    
    @Override
    public IBinder onBind(android.content.Intent intent) {
        return null;
    }
    
    // 摄像头预览视图
    private static class CameraPreviewView extends FrameLayout {
        private Surface surface;
        
        public CameraPreviewView(Context context) {
            super(context);
            // 这里需要实现SurfaceView或TextureView来显示摄像头预览
            // 为了简化，这里只是占位符
        }
        
        public Surface getSurface() {
            return surface;
        }
    }
}
